package com.mediacloud.app.newsmodule.fragment.baoliao.api;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.mediacloud.app.quanzi.model.ActivationRankingBean;
import com.mediacloud.app.quanzi.model.BaseDataBean;
import com.mediacloud.app.quanzi.model.BaseDataListBean;
import com.mediacloud.app.quanzi.model.DongTaiBean;
import com.mediacloud.app.quanzi.model.HuaTiBean;
import com.mediacloud.app.quanzi.model.PlaygroundGatherBean;
import com.mediacloud.app.quanzi.model.VoteStatus;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.user.net.JSONObjectConvertFactory;
import com.mediacloud.app.user.net.SSLSocketClient;
import com.mediacloud.app.user.net.SignInterceptor;
import com.mediaclound.appfactnet.utils.GETBadInterceptor;
import com.mediacloud.app.util.ProxyUtil;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.X509TrustManager;

import io.reactivex.Observable;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;

public class SpiderCmsLowApi {
    private static volatile SpiderCmsLowApi.ISpiderCmsLowApi spiderCmsLowApi;
    private static volatile SpiderCmsLowApi.ISpiderCmsLowApi spiderCmsLowApiJson;

    public static SpiderCmsLowApi.ISpiderCmsLowApi getSpiderCmsLowApi(Context context) {
        if (spiderCmsLowApi == null) {
            synchronized (SpiderCmsLowApi.class) {
                if (spiderCmsLowApi == null) {
                    initSpiderCmsLowApi(context.getApplicationContext());
                }
            }
        }
        return spiderCmsLowApi;
    }

    private static void initSpiderCmsLowApi(Context context) {
        String baseUrl = AppFactoryGlobalConfig.getAppServerConfigInfo(context).spider_cms_low;
        if (TextUtils.isEmpty(baseUrl)) {
            Log.e("DataInvokeUtil", "initSpiderCmsLowApi failed spider_cms is null");
            return;
        }
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.dns(new MyDns());
        ProxyUtil.config(builder);
        builder.protocols(Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2)));
        builder.addInterceptor(new SignInterceptor());
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).spider_cms_low,AppFactoryGlobalConfig.getAppServerConfigInfo(context).cdn_spider_cms_low));
        builder.addInterceptor(interceptor);
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("tenantId", context.getResources().getString(com.mediacloud.app.reslib.R.string.tenantid))
                    .build();
            return chain.proceed(request);
        });
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl + "/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        spiderCmsLowApi = retrofit.create(SpiderCmsLowApi.ISpiderCmsLowApi.class);
    }

    public static SpiderCmsLowApi.ISpiderCmsLowApi getSpiderCmsLowApiJson(Context context) {
        if (spiderCmsLowApiJson == null) {
            synchronized (SpiderCmsLowApi.class) {
                if (spiderCmsLowApiJson == null) {
                    initSpiderCmsLowApiJson(context.getApplicationContext());
                }
            }
        }
        return spiderCmsLowApiJson;
    }

    private static void initSpiderCmsLowApiJson(Context context) {
        String baseUrl = AppFactoryGlobalConfig.getAppServerConfigInfo(context).spider_cms_low;
        if (TextUtils.isEmpty(baseUrl)) {
            Log.e("DataInvokeUtil", "initSpiderCmsLowApiJson failed spider_cms is null");
            return;
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new SignInterceptor());
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).spider_cms_low,AppFactoryGlobalConfig.getAppServerConfigInfo(context).cdn_spider_cms_low));
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        ProxyUtil.config(builder);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("tenantId", context.getResources().getString(com.mediacloud.app.reslib.R.string.tenantid))
                    .build();
            return chain.proceed(request);
        });
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl + "/")
                .addConverterFactory(new JSONObjectConvertFactory())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        spiderCmsLowApiJson = retrofit.create(SpiderCmsLowApi.ISpiderCmsLowApi.class);
    }

    public interface ISpiderCmsLowApi {
        /**
         * 话题榜单首页（头部背景）
         */
        @GET("api/circleTopic/getTopicBanner")
        Call<BaseDataBean<String>> getHuaTiBangDanTopBg(@Header("tenantId") String tenantId);

        /**
         * 圈子首页/圈子搜索 推荐话题列表
         *
         * @param tenantId
         * @return
         */
        @GET("api/circleTopic/getRecommendTopics")
        Call<BaseDataBean<List<HuaTiBean>>> getTuiJianHuaTiList(@Header("tenantId") String tenantId);

        /**
         * 话题详情页
         */
        @GET("api/circleTopic/{id}")
        Call<BaseDataBean<HuaTiBean>> getHuaTiDetail(@Path("id") long id, @Header("tenantId") String tenantId);

//        api/circleTopic/share

        /**
         * 删除 动态/帖子
         */
        @POST("api/circleDynamic/delete/{id}")
        Call<BaseDataBean<String>> deleteDongTai(@Body RequestBody body, @Path("id") long id, @Header("tenantId") String tenantId);

        /**
         * 动态隐私性设置 公开、私有
         */
        @POST("api/circleDynamic/privacySet")
        Call<BaseDataBean<String>> modifyDongTaiPublic(@Body RequestBody body, @Header("tenantId") String tenantId);


        /**
         * 获取推荐视频动态列表
         */
        @POST("api/circleDynamic/recommendVideoDynamic")
        Call<BaseDataListBean<DongTaiBean>> getVideoDongTaiList(@Body RequestBody body, @Header("tenantId") String tenantId);

        /**
         * 获取最新话题列表
         * 获取最热话题列表
         * 话题搜索
         * 获取推荐话题列表
         */
        @POST("api/circleTopic/findPage")
        Call<BaseDataListBean<HuaTiBean>> getHuaTiList(@Body RequestBody body, @Header("tenantId") String tenantId);

        /**
         * 动态 - 查询最新动态
         */
        @GET("api/circleDynamic/pageNewest")
        Call<BaseDataListBean<DongTaiBean>> getNewDongTaiListForHuati(@QueryMap Map<String, Object> map);

        /**
         * 动态 - 查询热门动态
         */
        @GET("api/circleDynamic/pageHot")
        Call<BaseDataListBean<DongTaiBean>> getHotDongTaiListForHuati(@QueryMap Map<String, Object> map);

        /**
         * 动态 -- 投票
         * */
        @POST("api/circleDynamic/vote")
        Call<BaseDataBean<String>> chooseCircleVote(@Body RequestBody body);


        /**
         * 获取用户投票状态
         * */
        @GET("api/circleDynamic/vote/userVote")
        Call<BaseDataBean<List<VoteStatus>>> getVoteStatus(@QueryMap Map<String, Object> map);

        /**
         * 赞过的动态列表
         */
        @GET("api/circleDynamic/getMyPraisedDynamicPage")
        Call<BaseDataListBean<DongTaiBean>> getMyPraisedDongTaiList(@QueryMap Map<String, Object> map, @Header("tenantId") String tenantId);

        /**
         * 动态 - 查询榜单动态
         */
        @GET("api/circleDynamic/pageRanking")
        Call<BaseDataListBean<DongTaiBean>> getRankingDongTaiListForHuati(@QueryMap Map<String, Object> map);

        /**
         * 我的作品
         */
        @POST("api/circleDynamic/personalHomePage")
        Call<BaseDataListBean<DongTaiBean>> getAuthorDongTaiList(@Body RequestBody body, @Header("tenantId") String tenantId);

        /**
         * 获取最新动态列表(全部话题)
         * 获取最新动态列表(单个话题话题)
         * 动态搜索
         * 获取关注用户的动态列表
         */
        @POST("api/circleDynamic/findPage")
        Call<BaseDataListBean<DongTaiBean>> getAllDongTaiList(@Body RequestBody body, @Header("tenantId") String tenantId);

        @GET("api/circleDynamic/getCircleDynamicById/{id}")
        Call<BaseDataBean<DongTaiBean>> getDongtaiDetail(@Path("id") long id, @Header("tenantId") String tenantId);

        /**
         * 发布话题动态
         */
        @POST("api/circleDynamic/save")
        Call<BaseDataBean<JSONObject>> submitDongTai(@Body RequestBody body, @Header("tenantId") String tenantId);

        /**
         * 动态 - 搜索(注：替换原搜索动态的接口)
         * pageSize	是	Integer	单页数据量
         * pageNumber	是	Integer	当前页码
         * keyword	是	String	搜索关键词
         */
        @GET("api/circleDynamic/search")
        Call<BaseDataListBean<DongTaiBean>> getSearchCircleDynamicList(@Query("keyword") String keyword,
                                                                       @Query("pageNumber") String pageNumber,
                                                                       @Query("pageSize") String pageSize, @Header("tenantId") String tenantId);

        /**
         * 话题 - 成员活跃度排行榜
         */
        @GET("api/circleTopic/ranking/memberActivation")
        Call<BaseDataBean<ActivationRankingBean>> getActivationRankingListForHuati(@Query("topicId") long topicId);

        /**
         * 话题 - 查询话题广场
         */
        @GET("api/circleTopic/ground")
        Call<BaseDataBean<List<PlaygroundGatherBean>>> getPlaygroundGatherList();

        /**
         * 获取加入的话题
         */
        @GET("api/circleTopic/pageUserFollowed")
        Observable<JSONObject> getJoinTopic(@Query("userId") String userId);

        /**
         * 获取活跃榜单
         */
        @GET("api/circleTopic/ranking/memberActivation")
        Observable<JSONObject> getCharts(@Query("topicId") String topicId);

        /**
         * 获取创作榜单
         */
        @GET("api/circleTopic/ranking/postCount")
        Observable<JSONObject> getCharts2(@Query("topicId") String topicId);

        /**
         * 话题 - 获取话题权限信息
         * userId	否	long	用户ID，可选，指定此参数时查询用户缺失的权限
         * topicIds	是	string	话题ID，多个时使用,分割
         *
         * @return
         */
        @GET("api/circleTopic/authorities")
        Observable<JSONObject> getTopicAuthorities(@Query("userId") String userId, @Query("topicIds") String topicIds);
        /**
         * 话题 - 用户是否关注
         * userId	是	long	用户ID
         * topicIds	是	string	话题ID，多个时用,分割
         *
         * @return
         */
        @GET("api/circleTopic/userFollowed")
        Call<BaseDataBean<List<String>>> getTopicFollowList(@Query("userId") String userId, @Query("topicIds") String topicIds);

    }
}
